package DAO1;

//代理类作为中间层，包裹真实的DAO实现，增强其功能而不侵入业务代码。
//业务代码不需要知道事务的存在，由代理在方法调用前后处理事务的开启和提交。
import java.util.List;

//代理操作IWorkerDAo中的业务需求
public class WorkerDAOProxy implements IWorkerDAO {
    private DatabaseConnection db = null ;
    private IWorkerDAO dao = null ;

    //    代理建立连接数据库
    public WorkerDAOProxy() throws Exception {
        this.db = new DatabaseConnection() ;
        this.dao = new WorkerDAOImpl(this.db.getConnection()) ;
    }
    //    代理实现注册功能
    public boolean doCreate(Worker work) throws Exception{
        boolean flag = false ;
        try{
            if(this.dao.findById(work.getEmpno()) == null){
                flag = this.dao.doCreate(work) ;
            }
        }catch(Exception e){
            throw e ;
        }finally{
            this.db.close() ;
        }
        return flag ;
    }
    //    代理实现查询用户功能
    public List<Worker> findAll(String keyWord) throws Exception{
        List<Worker> all = null ;
        try{
            all = this.dao.findAll(keyWord) ;
        }catch(Exception e){
            throw e ;
        }finally{
            this.db.close() ;
        }
        return all ;
    }
    //    代理通过id查询用户的功能
    public Worker findById(int empno) throws Exception {
        Worker emp = null;
        try {
            emp = this.dao.findById(empno);
        } catch (Exception e) {
            throw e;
        } finally {
            this.db.close();
        }
        return emp;
    }
}

